package com.vhall.component.service.anchors.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.anchors.AnchorManageMapper;
import com.vhall.component.dao.room.AnchorRoomLkMapper;
import com.vhall.component.entity.anchors.AnchorManageEntity;
import com.vhall.component.entity.anchors.dto.AnchorManagePageRspListVO;
import com.vhall.component.entity.anchors.vo.AnchorManageCreateVO;
import com.vhall.component.entity.anchors.vo.AnchorManagePageListVO;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.room.entity.AnchorRoomLkEntity;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.enums.DeleteStatusEnum;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.utils.BeanCopyUtil;
import com.vhall.component.service.anchors.AnchorManageService;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Preconditions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * <p>
 * 主播表 服务实现类
 * </p>
 *
 * @author wangxing
 * @since 2022-09-28
 */
@Service
public class AnchorManageServiceImpl extends ServiceImpl<AnchorManageMapper, AnchorManageEntity> implements AnchorManageService {

    private static final int MAX_NUM = 3;

    @Resource
    private AnchorRoomLkMapper anchorRoomLkMapper;

    @Override
    public Boolean create(AnchorManageCreateVO vo) {

        basicValidate(vo);

        AnchorManageEntity entity = new AnchorManageEntity();
        BeanUtil.copyProperties(vo, entity);

        Random random = new Random();
        int num = random.nextInt(5) + 1;

        entity.setBackColorOfHead(num);
        int insert = baseMapper.insert(entity);
        return insert > 0;
    }

    private void basicValidate(AnchorManageCreateVO vo) {
        String careerId = vo.getCareerId();
        if (StringUtils.isNotBlank(careerId)) {
            LambdaQueryWrapper<AnchorManageEntity> where = Wrappers.lambdaQuery();
            where.eq(AnchorManageEntity::getCareerId, careerId);
            where.eq(AnchorManageEntity::getDeleted, DeleteStatusEnum.NO_DELETE.getStatus());
            AnchorManageEntity anchorManageEntity = baseMapper.selectOne(where);
            Preconditions.checkArgument(anchorManageEntity == null
                    || vo.getAnchorId() != null && anchorManageEntity.getAnchorId().equals(vo.getAnchorId()), "执业编号已存在，请重试");

        }
    }


    @Override
    public Boolean update(AnchorManageCreateVO vo) {
        Preconditions.checkArgument(vo.getAnchorId() != null, "AnchorId cannot be null");
        basicValidate(vo);

        AnchorManageEntity entity = new AnchorManageEntity();
        BeanUtil.copyProperties(vo, entity);

        return updateById(entity);
    }

    @Override
    public Boolean delete(List<Integer> ids) {

        // 已经关联房间的讲师，禁止删除
        LambdaQueryWrapper<AnchorRoomLkEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.in(AnchorRoomLkEntity::getAnchorId, ids);
        List<AnchorRoomLkEntity> anchorRoomLkEntities = anchorRoomLkMapper.selectList(wrapper);
        Preconditions.checkArgument(CollectionUtil.isEmpty(anchorRoomLkEntities), "已被直播间关联，无法删除，请取消关联后重试！");

        List<AnchorManageEntity> list = new ArrayList<>();

        for (Integer anchorId : ids) {
            AnchorManageEntity entity = new AnchorManageEntity();
            entity.setDeleted(DeleteStatusEnum.DELETE.getStatus());
            entity.setAnchorId(anchorId);
            list.add(entity);
        }
        boolean updateResult = updateBatchById(list);
        return updateResult;
    }


    @Override
    public PageVO<AnchorManagePageRspListVO> pageList(AnchorManagePageListVO vo) {

        LambdaQueryWrapper<AnchorManageEntity> where = Wrappers.lambdaQuery();
        where.eq(AnchorManageEntity::getDeleted, DeleteStatusEnum.NO_DELETE.getStatus());
        if (CollectionUtil.isNotEmpty(vo.getExcludeLecturerIds())) {
            where.notIn(AnchorManageEntity::getAnchorId, vo.getExcludeLecturerIds());
        }
        where.and(StringUtils.isNotBlank(vo.getKeyword()), wq -> wq.eq(AnchorManageEntity::getCareerId, vo.getKeyword())
                .or()
                .like(AnchorManageEntity::getRealName, vo.getKeyword())
                );

        where.orderByDesc(AnchorManageEntity::getAnchorId);

        Integer pageIndex = vo.getPage();
        Integer pageSize = vo.getPageSize();
        Page<AnchorManageEntity> page = new Page<>(pageIndex, pageSize);
        Page<AnchorManageEntity> quickRepliesEntityPage = baseMapper.selectPage(page, where);
        List<AnchorManagePageRspListVO> list = new ArrayList<>();

        if (Objects.nonNull(quickRepliesEntityPage) && quickRepliesEntityPage.getTotal() > 0) {
            list = BeanCopyUtil.batchCopy(quickRepliesEntityPage.getRecords(), AnchorManagePageRspListVO::new);
            list.forEach(e -> e.setNickName(e.getRealName()));
        }

        return new PageVO<>(pageIndex, pageSize, (int) page.getTotal(), list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean recommend(AnchorManageCreateVO vo) {
        Preconditions.checkArgument(vo.getAnchorId() != null, "AnchorId cannot be null");
        Preconditions.checkArgument(vo.getRecommend() != null, "是否推荐 不能为空！");

        AnchorManageEntity entity = new AnchorManageEntity();
        entity.setRecommend(vo.getRecommend());
        entity.setAnchorId(vo.getAnchorId());
        baseMapper.updateById(entity);

        LambdaQueryWrapper<AnchorManageEntity> where = Wrappers.lambdaQuery();
        where.eq(AnchorManageEntity::getRecommend, 1);
        where.eq(AnchorManageEntity::getDeleted, DeleteStatusEnum.NO_DELETE.getStatus());
        if (baseMapper.selectCount(where) > MAX_NUM) {
            throw new BusinessException(BizErrorCode.BIZ_ANCHOR_RECOMMAND_SIEZE_ERROR);
        }

        return true;
    }


}
